from typing import TypeVar, Generic, Sequence, Optional
from pydantic import BaseModel, conint
from fastapi import Query

T = TypeVar("T")

class PageParams(BaseModel):
    """
    分页参数模型
    """
    page: conint(ge=1) = Query(1, description="页码")
    page_size: conint(ge=1, le=100) = Query(10, description="每页数量")

class Page(BaseModel, Generic[T]):
    """
    分页响应模型
    """
    items: Sequence[T]
    total: int
    page: int
    page_size: int
    pages: int

def paginate(
    items: Sequence[T],
    page: int,
    page_size: int,
    total: Optional[int] = None
) -> Page[T]:
    """
    对序列进行分页
    
    Args:
        items: 要分页的项目序列
        page: 当前页码
        page_size: 每页数量
        total: 总数（如果不提供，将使用items的长度）
    
    Returns:
        Page[T]: 分页结果
    """
    if total is None:
        total = len(items)
    
    pages = (total + page_size - 1) // page_size
    
    return Page(
        items=items,
        total=total,
        page=page,
        page_size=page_size,
        pages=pages
    )